package com.example.coursedesign.ui.dashboard;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.example.coursedesign.R;
import com.example.coursedesign.databinding.FragmentDashboardBinding;
import com.example.coursedesign.ui.dashboard.adapter.ScienceAdapter;
import com.example.coursedesign.ui.dashboard.dao.ScienceDao;
import com.example.coursedesign.ui.dashboard.entity.Science;
import com.example.coursedesign.ui.dashboard.ScienceDetail; // 假设 ScienceDetail 是你的详情页 Activity

import java.util.List;

public class DashboardFragment extends Fragment {

    private static final String TAG = "DashboardFragment";
    private FragmentDashboardBinding binding;
    private ScienceAdapter scienceAdapter;
    private RecyclerView recyclerView;
    private ScienceDao scienceDao;
    private String selectedCategory = "全部"; // 默认为“全部”类别

    // 创建 ActivityResultLauncher 实例
    private final ActivityResultLauncher<Intent> activityResultLauncher =
            registerForActivityResult(
                    new ActivityResultContracts.StartActivityForResult(),
                    result -> {
                        if (result.getResultCode() == AppCompatActivity.RESULT_OK) {
                            // 当用户从详情页返回时，重新加载所选类别的文章列表
                            loadSciences(selectedCategory);
                        }
                    });

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView called");

        DashboardViewModel dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);

        binding = FragmentDashboardBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 初始化RecyclerView和适配器
        recyclerView = binding.recyclerView;
        scienceAdapter = new ScienceAdapter(getContext(), this::onScienceItemClick);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(scienceAdapter);

        // 初始化类别 TextView 数组
        TextView[] categoryTextViews = new TextView[]{
                binding.categoryAll,
                binding.categoryPsoriasis,
                binding.categoryEczema,
                binding.categoryAcne,
                binding.categoryFrostbite
        };

        // 设置类别选择器点击监听器
        setupCategoryListeners(categoryTextViews);

        // 设置搜索框的监听器
        setupSearchView();

        // 设置搜索按钮的点击监听器
        setupSearchButtonListener();

        // 默认选中“全部”类别
        updateCategorySelection(binding.categoryAll);

        // 加载默认数据（例如“全部”类别）
        loadSciences("全部");

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void setupCategoryListeners(TextView[] categoryTextViews) {
        for (TextView categoryTextView : categoryTextViews) {
            categoryTextView.setOnClickListener(this::onCategoryClick);
        }
    }

    private void onCategoryClick(View view) {
        TextView clickedTextView = (TextView) view;
        selectedCategory = clickedTextView.getText().toString();

        // 更新文本颜色和下划线显示
        updateCategorySelection(clickedTextView);

        // 加载所选类别的数据
        loadSciences(selectedCategory);
    }

    private void updateCategorySelection(TextView selectedTextView) {
        int selectedColor = ContextCompat.getColor(getContext(), R.color.selected_color);
        int defaultColor = ContextCompat.getColor(getContext(), R.color.default_color);

        for (TextView categoryTextView : new TextView[]{
                binding.categoryAll,
                binding.categoryPsoriasis,
                binding.categoryEczema,
                binding.categoryAcne,
                binding.categoryFrostbite}) {
            if (categoryTextView == selectedTextView) {
                categoryTextView.setTextColor(selectedColor);
                getUnderlineByCategory(categoryTextView).setVisibility(View.VISIBLE);
            } else {
                categoryTextView.setTextColor(defaultColor);
                getUnderlineByCategory(categoryTextView).setVisibility(View.GONE);
            }
        }
    }

    // 根据选择的 TextView 获取对应的下划线
    private View getUnderlineByCategory(TextView categoryTextView) {
        switch (categoryTextView.getId()) {
            case R.id.categoryAll:
                return binding.categoryAllUnderline;
            case R.id.categoryPsoriasis:
                return binding.categoryPsoriasisUnderline;
            case R.id.categoryEczema:
                return binding.categoryEczemaUnderline;
            case R.id.categoryAcne:
                return binding.categoryAcneUnderline;
            case R.id.categoryFrostbite:
                return binding.categoryFrostbiteUnderline;
            default:
                return null;
        }
    }

    private void loadSciences(String category) {
        Log.d(TAG, "Loading sciences for category: " + category);
        // 使用异步任务或后台线程加载数据，避免阻塞主线程
        new LoadSciencesTask(category).execute();
    }

    private class LoadSciencesTask extends AsyncTask<String, Void, List<Science>> {
        private final String category;

        LoadSciencesTask(String category) {
            this.category = category;
        }

        @Override
        protected List<Science> doInBackground(String... params) {
            try {
                scienceDao = new ScienceDao();
                if ("全部".equals(category)) {
                    return scienceDao.getAllSciences();
                } else {
                    return scienceDao.getSciencesByCategory(category);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error in loadSciences: " + e.getMessage(), e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<Science> sciences) {
            Log.d(TAG, "Loaded sciences size: " + (sciences != null ? sciences.size() : "null"));
            if (sciences != null) {
                scienceAdapter.setScienceList(sciences);
                recyclerView.setAdapter(scienceAdapter); // 确保适配器被重新设置
            } else {
                Log.e(TAG, "Received null science list from loadSciences");
            }
        }
    }

    private void setupSearchView() {
        binding.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.d(TAG, "Search submitted: " + query);
                if (!query.isEmpty()) {
                    filterSciences(query);
                } else {
                    // 如果查询为空，加载默认的类别数据
                    loadSciences(selectedCategory);
                }
                // 隐藏键盘（可选）
                binding.searchView.clearFocus();
                return true; // 表示事件已处理
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Log.d(TAG, "Search text changed: " + newText);
                if (newText.isEmpty()) {
                    // 当输入框内容为空时，重新加载默认类别的数据
                    loadSciences(selectedCategory);
                }
                // 不再在此处执行搜索操作
                return false;
            }
        });

        // 添加关闭监听器以处理清除按钮点击事件
        binding.searchView.setOnCloseListener(() -> {
            Log.d(TAG, "Search closed/cleared");
            // 当关闭或清除搜索时，加载默认类别的数据
            loadSciences(selectedCategory);
            return false; // 返回false表示允许关闭
        });
    }

    private void setupSearchButtonListener() {
        binding.searchButton.setOnClickListener(v -> {
            String query = binding.searchView.getQuery().toString();
            Log.d(TAG, "Search button clicked with query: " + query);
            if (!query.isEmpty()) {
                filterSciences(query);
            } else {
                // 如果查询为空，加载默认的类别数据
                loadSciences(selectedCategory);
            }
        });
    }

    private void filterSciences(String query) {
        Log.d(TAG, "Filtering sciences with query: " + query);
        if (query.isEmpty()) {
            // 如果查询为空，加载默认的类别数据
            loadSciences(selectedCategory);
        } else {
            // 执行搜索操作
            new FilterSciencesTask(query).execute();
        }
    }

    private class FilterSciencesTask extends AsyncTask<String, Void, List<Science>> {
        private final String query;

        FilterSciencesTask(String query) {
            this.query = query;
        }

        @Override
        protected List<Science> doInBackground(String... params) {
            try {
                scienceDao = new ScienceDao();
                List<Science> result = scienceDao.searchSciences(query);
                Log.d(TAG, "Search results size: " + (result != null ? result.size() : "null"));
                return result;
            } catch (Exception e) {
                Log.e(TAG, "Error in searchSciences: " + e.getMessage(), e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<Science> sciences) {
            Log.d(TAG, "Setting science list to adapter");
            if (sciences != null) {
                scienceAdapter.setScienceList(sciences);
                recyclerView.setAdapter(scienceAdapter); // 确保适配器被重新设置
            } else {
                Log.e(TAG, "Received null science list from searchSciences");
            }
        }
    }

    private void onScienceItemClick(Science science) {
        Intent intent = new Intent(getContext(), ScienceDetail.class);
        intent.putExtra("science_id", science.getId()); // 假设 Science 对象有一个 getId() 方法

        // 使用 ActivityResultLauncher 启动 ScienceDetailActivity 并等待结果
        activityResultLauncher.launch(intent);
    }
}